﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using AEM.Data;
using Actions = AEM.Data.BLL.Actions;

namespace AEM.Controls
{
    /// <summary>
    /// GroupControl.xaml 的交互逻辑
    /// </summary>
    public partial class GroupControl : UserControl
    {
        /// <summary>
        /// 关闭委托
        /// </summary>
        public event EventHandler<EventArgs> CloseEventHandler;
        public event EventHandler<EventArgs> CompleteEventHandler;
        public static int[] _liftnums;
        private Point _startPoint;
        public GroupControl()
        {
            InitializeComponent();
            this.group_name.MouseLeftButtonDown += new MouseButtonEventHandler(GroupControl_MouseLeftButtonDown);
            this.group_name.MouseMove += new MouseEventHandler(GroupControl_MouseMove);
            this.group_name.MouseUp += new MouseButtonEventHandler(GroupControl_MouseUp);
            this.sys_button_close.Click += new RoutedEventHandler(sys_button_close_Click);
            this.Loaded += new RoutedEventHandler(GroupControl_Loaded);

        }

        void GroupControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (null != CompleteEventHandler)
                CompleteEventHandler.Invoke(this, new EventArgs());
        }

        #region 拖动功能
        void GroupControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _startPoint = e.GetPosition(null);
        }
        void GroupControl_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Point position = e.GetPosition(null);
                if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    this.StartDrag(e);
                }
            }
        }
        void GroupControl_MouseUp(object sender, MouseButtonEventArgs e)
        {
            double left = this.Margin.Left;
            double top = this.Margin.Top;
            Actions.LiftInfo.ModifiyGroupMargin(this.GroupID, left, top);
        }

        private void StartDrag(MouseEventArgs e)
        {
            Point thisPoint = e.GetPosition(null);
            double left = 0, top = 0;
            left = this.Margin.Left;
            top = this.Margin.Top;
            left = thisPoint.X - _startPoint.X + left;
            top = thisPoint.Y - _startPoint.Y + top;
            double maxtop = System.Windows.SystemParameters.WorkArea.Height - this.Height;
            double maxleft = System.Windows.SystemParameters.WorkArea.Width - this.MaxWidth;
            if (left > maxleft) left = maxleft;
            if (top > maxtop) top = maxtop;
            if (left < 10) left = 10;
            if (top < 0) top = 0;
            this.Margin = new Thickness(left, top, 0, 0);

            _startPoint = thisPoint;
        }
        #endregion

        /// <summary>
        /// 关闭
        /// </summary>
        void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            if (null != CloseEventHandler)
                this.CloseEventHandler.BeginInvoke(this, e, new AsyncCallback(CallBack), null);
        }
        private void CallBack(IAsyncResult tag)
        {
            AsyncResult result = (AsyncResult)tag;
            EventHandler<EventArgs> del = (EventHandler<EventArgs>)result.AsyncDelegate;
            del.EndInvoke(tag);
        }

        private static void OnGroupIDChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue != args.OldValue)
            {
                int gid = (int)args.NewValue;
                if (0 == gid) return;
                List<Data.Model.LiftInfo> list = (from l in Config.LiftInftList
                                                  where l.LiftGroup == gid & l.LiftType == (int)Data.Enum.LiftType.电梯
                                                  select l).ToList();
                if (null == list) { (sender as GroupControl).group_name.Content = (sender as GroupControl).TryFindResource("NoID") as string; return; }
                (sender as GroupControl).group_name.Content = ((sender as GroupControl).TryFindResource("Group") as string) + " " + (int)args.NewValue;
                InitGroupInfo(sender as GroupControl, list.ToArray());
            }
        }

        private static void InitGroupInfo(GroupControl model, Data.Model.LiftInfo[] rows)
        {
            int i = 0;
            model.lift_group.Children.Clear();

            int MaxFloors = (from Data.Model.LiftInfo l in rows
                             select l.LiftActualFloor.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length).Max();
            int FloorHeight = AEM.Properties.Settings.Default.FloorHeight;
            if (10 > FloorHeight) FloorHeight = 10;
            if (FloorHeight == 10)
            {
                if (MaxFloors <= 64) FloorHeight = 10;
                if (MaxFloors <= 48) FloorHeight = 13;
                if (MaxFloors <= 32) FloorHeight = 15;
                if (MaxFloors <= 16) FloorHeight = 30;
            }

            //添加外招 控件
            OuterRingModel orm = new OuterRingModel();
            model.RegisterName("outerRingModel", orm);
            orm.Width = 20;
            orm.FloorHeight = FloorHeight;
            orm.MaxFloors = MaxFloors;

            model.lift_group.Children.Add(orm);
            model.MaxWidth = model.MinWidth += 20;
            _liftnums = new int[rows.Length];
            foreach (Data.Model.LiftInfo r in rows)
            {
                _liftnums[i] = r.LiftNum;
                Image img = new Image();
                img.Source = new BitmapImage(new Uri("pack://application:,,,/Config/Default/Images/Group/group_splitline.png"));
                img.Width = 10;
                LiftModel l = new LiftModel();

                l.FloorHeight = FloorHeight;
                l.MaxFloors = MaxFloors;

                model.RegisterName("l" + r.LiftNum, l);
                l.Name = "l" + r.LiftNum;
                l.LiftID = r.ID;
                l.VerticalAlignment = VerticalAlignment.Top;
                //orm.Floors = r.LiftActualFloor;

                if (i < 5)
                {
                    model.lift_group.Children.Insert(i * 2, l);
                    model.lift_group.Children.Insert(i * 2 + 1, img);
                }
                if (i >= 5)
                {
                    model.lift_group.Children.Add(img);
                    model.lift_group.Children.Add(l);
                }

                model.MaxWidth = model.MinWidth += l.Width + 10;
                model.Height = model.MinHeight = model.MaxHeight = Math.Max(model.MinHeight, l.Height + 100);
                i++;
            }

        }

        private static void OnLiftRuningChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            GroupControl gc = (GroupControl)sender;
            if (args.NewValue != args.OldValue)
            {
                try
                {
                    var e = (SerialDataEventArgs)args.NewValue;
                    if (null == e) return;
                    var l = (LiftModel)gc.FindName("l" + e.LiftNum);
                    if (null == l) return;
                    l.LiftRising = e.Data.Rising;
                    l.LiftDescending = e.Data.Descending;
                    //l.DoorStatus = e.Data.DoorClose ? false : true;
                    l.DoorStatus = e.Data.DoorOpen;
                    //电梯状态
                    Data.Enum.LiftStatus ls = Data.Enum.LiftStatus.Normal;
                    if (e.Data.Dirver) ls = Data.Enum.LiftStatus.Driver;
                    if (e.Data.Overhaul) ls = Data.Enum.LiftStatus.Overhaul;
                    if (e.Data.Locked) ls = Data.Enum.LiftStatus.Locked;
                    if (e.Data.Fire) ls = Data.Enum.LiftStatus.Fire;
                    if (e.Data.FaultLamp || e.Data.ConverterAlarm || e.Data.CageAlarm || e.Data.IsEarthquaked) ls = Data.Enum.LiftStatus.Fault;
                    string[] floorarr = e.LiftInfo.LiftActualFloor.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i=0;i< floorarr.Length;i++)
                    {
                        if (floorarr[i].PadLeft(2, '0') == e.FloorShow.PadLeft(2, '0'))
                        {
                            l.FloorNow =(i+1).ToString();// e.Floor.ToString();
                            break;
                        }
                    }
                    l.LiftStatus = ls;

                    l.InnerRing = e.Data.InnerRing;
                    //l.FloorNow = e.Floor.ToString();
                    //Console.WriteLine(DateTime.Now.ToString() + "---" + l.FloorNow);
                    System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString()+"---"+l.FloorNow);
                    var of = (OuterRingModel)gc.FindName("outerRingModel");
                    of.UpRing = e.Data.OuterUpRing;
                    of.DownRing = e.Data.OuterDownRing;
                }
                catch { }
            }
        }

        private static void OnLiftNCChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            GroupControl gc = (GroupControl)sender;
            //if (args.NewValue != args.OldValue)
            //{

            var num = (int)args.NewValue;
            if (num > 0)
            {
                var l = (LiftModel)gc.FindName("l" + num);
                if (null != l)
                    l.LiftStatus = Data.Enum.LiftStatus.NC;
            }
            //}
        }

        #region 注册属性
        /// <summary>
        /// 电梯组ID
        /// </summary>
        public static readonly DependencyProperty GroupIDProperty =
            DependencyProperty.Register("GroupID", typeof(int), typeof(GroupControl),
            new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnGroupIDChanged)));

        /// <summary>
        /// 电梯组ID
        /// </summary>
        public int GroupID
        {
            get { return (int)GetValue(GroupIDProperty); }
            set { SetValue(GroupIDProperty, value); }
        }

        public static readonly DependencyProperty LiftRuningProperty =
            DependencyProperty.Register("LiftRuning", typeof(SerialDataEventArgs), typeof(GroupControl),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnLiftRuningChanged)));

        public SerialDataEventArgs LiftRuning
        {
            get { return (SerialDataEventArgs)GetValue(LiftRuningProperty); }
            set { SetValue(LiftRuningProperty, value); }
        }

        public static readonly DependencyProperty LiftNCProperty =
            DependencyProperty.Register("LiftNC", typeof(int), typeof(GroupControl),
            new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnLiftNCChanged)));
        public int LiftNC
        {
            get { return (int)GetValue(LiftNCProperty); }
            set { SetValue(LiftNCProperty, value); }
        }

        public int[] LiftNums
        {
            get { return _liftnums; }
        }
        #endregion
    }
}
